package org.urchr.beorganized.mobile.pages.secured.edit;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.wicket.PageParameters;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.Radio;
import org.apache.wicket.markup.html.form.RadioGroup;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.CompoundPropertyModel;
import org.urchr.beorganized.mobile.base.Application;
import org.urchr.beorganized.mobile.base.MobileSession;
import org.urchr.beorganized.mobile.base.components.link.MobileLink;
import org.urchr.beorganized.mobile.base.network.NetworkException;
import org.urchr.beorganized.mobile.base.network.XMLRequest;
import org.urchr.beorganized.mobile.pages.secured.base.SecuredPage;
import org.urchr.beorganized.mobile.pages.secured.browse.BrowsePage;
import org.w3c.dom.Element;

import sun.misc.Cleaner;

public class EditPage extends SecuredPage {

	private String name = "";
	private String url = "";
	private boolean complete = false;
	private int priority = 0;
	private String dueDate = "";
	private String startDate = "";
	private String endDate = "";
	private String textContent = "";
	
	private int r0 = 0;
	private int r1 = 1;
	private int r2 = 2;
	
	public EditPage(PageParameters parameters) {
		super(parameters);
		final int noteID = parameters.getAsInteger("id", -1);
		add(new MobileLink("back", "action/top.png", 
				new BookmarkablePageLink("clink", BrowsePage.class, 
						new PageParameters("id="+noteID)), "Go back"));
		resetError();
		XMLRequest request = new XMLRequest("GetNote");
		request.addParameter("noteid", ""+noteID);
		try {
			final Element e = request.callOperation();
			final boolean newNote = parameters.getAsBoolean("new", false);
			final int type = newNote?parameters.getAsInteger("type", 0):safeInt(e.getAttribute("type"), 0);
			final SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
			final SimpleDateFormat dateFormat = new SimpleDateFormat(MobileSession.getSession().getDateFormat());
			final SimpleDateFormat dateTimeFormat = new SimpleDateFormat(MobileSession.getSession().getDateFormat()+" "+
					MobileSession.getSession().getTimeFormat());
			Form form = new Form("form"){
				private static final long serialVersionUID = -2591999489336698615L;
				
				@Override
				protected void onSubmit() {
					resetError();
					XMLRequest request = new XMLRequest("SaveNote");
					request.addParameter("id", noteID);
					request.addParameter("type", type);
					request.addParameter("name", getName());
					if(!newNote){
						request.addParameter("customIcon", e.getAttribute("customIcon"));
					}
					request.addParameter("textContent", getTextContent());
					request.addParameter("savetags", "false");
					request.addParameter("newNote", newNote?"true":"false");
					request.addParameter("rnd", Application.genRandomString());
					switch (type) {
					case Application.TYPE_TASK:
						request.addParameter("completed", complete?"true":"false");
						request.addParameter("priority", priority);
						try {
							Date date = dateFormat.parse(getDueDate());
							request.addParameter("startDate", isoFormat.format(date));
						} catch (Exception e2) {
						}
						break;
					case Application.TYPE_EVENT:
						try {
							Date date = dateTimeFormat.parse(getStartDate());
							request.addParameter("startDate", isoFormat.format(date));
						} catch (Exception e2) {
						}
						try {
							Date date = dateTimeFormat.parse(getEndDate());
							request.addParameter("endDate", isoFormat.format(date));
						} catch (Exception e2) {
						}
						break;
					case Application.TYPE_BMARK:
						request.addParameter("url", getUrl());
						break;
					}
					try {
						Element e = request.callOperation();
						setResponsePage(BrowsePage.class, new PageParameters("id="+e.getAttribute("id")));
					} catch (NetworkException e) {
						e.printStackTrace();
						showError(e.getErrorString());
					}
				}
			};
			form.setModel(new CompoundPropertyModel<EditPage>(this));
			form.add(new TextField<String>("name"));
			setName(newNote?"":e.getAttribute("text"));
			
			form.add(new Label("url").setVisible(false));
			form.add(new Label("complete").setVisible(false));
			form.add(new Label("priority").setVisible(false));
			form.add(new Label("dueDate").setVisible(false));
			form.add(new Label("startDate").setVisible(false));
			form.add(new Label("endDate").setVisible(false));
			String title = "";
			switch (type) {
			case Application.TYPE_TEXT:
				title = newNote?"New text note":"Edit text note";
				break;
			case Application.TYPE_TASK:
				title = newNote?"New task":"Edit task";
				setComplete(newNote?false:"true".equals(e.getAttribute("completed")));
				setPriority(newNote?2:safeInt(e.getAttribute("priority"), 2));
				form.addOrReplace(new CheckBox("complete"));
				RadioGroup<Integer> radioGroup = new RadioGroup<Integer>("priority");
				for (int i = 0; i < 3; i++) {
					Radio<Integer> radio = new Radio<Integer>("r"+i);
					radio.add(new Image("i"+i).add(
							new SimpleAttributeModifier("src", 
									Application.IMG_PREFIX+"priority/p"+i+".png")));
					radioGroup.add(radio);
				}
				form.addOrReplace(radioGroup);
				form.addOrReplace(new Label("dateFormat", 
						MobileSession.getSession().getDateFormat().toLowerCase()));
				if(!newNote){
					try {
						Date date = isoFormat.parse(e.getAttribute("startDate"));
						setDueDate(dateFormat.format(date));
					} catch (Exception e2) {
					}
				}
				form.addOrReplace(new TextField<String>("dueDate"));
				break;
			case Application.TYPE_EVENT:
				title = newNote?"New event":"Edit event";
				if(!newNote){
					try {
						Date date = isoFormat.parse(e.getAttribute("startDate"));
						setStartDate(dateTimeFormat.format(date));
					} catch (Exception e2) {
					}
					try {
						Date date = isoFormat.parse(e.getAttribute("endDate"));
						setEndDate(dateTimeFormat.format(date));
					} catch (Exception e2) {
					}
				}else{
					Calendar c = Calendar.getInstance();
					c.add(Calendar.MILLISECOND, -c.get(Calendar.ZONE_OFFSET));
					c.add(Calendar.MINUTE, MobileSession.getSession().getMinuteOffset());
					if(c.get(Calendar.MINUTE)>0){
						c.set(Calendar.MINUTE, 0);
						c.add(Calendar.HOUR, 1);
					}
					try {
						setStartDate(dateTimeFormat.format(c.getTime()));
						c.add(Calendar.HOUR, 1);					
						setEndDate(dateTimeFormat.format(c.getTime()));						
					} catch (Exception e2) {
					}
				}
				form.addOrReplace(new TextField<String>("startDate"));
				form.addOrReplace(new TextField<String>("endDate"));
				break;
			case Application.TYPE_BMARK:
				title = newNote?"New bookmark":"Edit bookmark";
				setUrl(newNote?"http://":e.getAttribute("url"));
				form.addOrReplace(new TextField<String>("url"));
				break;
			}
			
			form.add(new TextArea<String>("textContent"));
			setTextContent(newNote?"":e.getAttribute("textContent"));
			
			form.add(new Label("title", title+":"));
			add(form);
		} catch (NetworkException e) {
			e.printStackTrace();
			add(new Label("form").setVisible(false));
			showError(e.getErrorString());
		}
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl() {
		return url;
	}

	public void setComplete(boolean complete) {
		this.complete = complete;
	}

	public boolean isComplete() {
		return complete;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}

	public int getPriority() {
		return priority;
	}

	public void setDueDate(String dueDate) {
		this.dueDate = dueDate;
	}

	public String getDueDate() {
		return dueDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setTextContent(String textContent) {
		this.textContent = textContent;
	}

	public String getTextContent() {
		return textContent;
	}

	public void setR0(int r0) {
		this.r0 = r0;
	}

	public int getR0() {
		return r0;
	}

	public void setR1(int r1) {
		this.r1 = r1;
	}

	public int getR1() {
		return r1;
	}

	public void setR2(int r2) {
		this.r2 = r2;
	}

	public int getR2() {
		return r2;
	}

}
